<?php

/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

    public $helpers = array(
        'Session',
        'Search.Prg',
        'Html' => array('className' => 'BoostCake.BoostCakeHtml'),
        'Form' => array('className' => 'BoostCake.BoostCakeForm'),
        'Paginator' => array('className' => 'BoostCake.BoostCakePaginator'),
        'Formatacao' => array('className' => 'CakePtbr.Formatacao'),
    );
    public $components = array(
        'Session',
        'Auth',
        'DebugKit.Toolbar',
        'CakePtbr.Export',
        'Paginator',
        'Session',
        'Search.Prg',
        'RequestHandler'
    );

    public function beforeFilter() {
        Configure::write('Config.language', 'pt_br');
        $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login', 'admin' => false);
        $this->Auth->loginRedirect = array('controller' => 'orders', 'action' => 'index', 'admin' => true);
        $this->Auth->logoutRedirect = array('controller' => 'products', 'action' => 'index', 'admin' => false);
        $this->Auth->authorize = array('Controller');

        $this->Auth->authenticate = array(
            AuthComponent::ALL => array(
                'recursive' => 2,
                'userModel' => 'User',
                'fields' => array(
                    'username' => 'username',
                    'password' => 'password'
                ),
                'scope' => array(
                    'User.active' => 1,
                )
            ),
            'Form'
        );

        if (isset($this->request->params['admin']) && ($this->request->params['prefix'] == 'admin')) {
            if ($this->Session->check('Auth.User')) {
                $this->set('authUser', $this->Auth->user());
                $loggedin = $this->Session->read('Auth.User');
                $this->set(compact('loggedin'));
                $this->layout = 'admin';
            }
        } elseif (isset($this->request->params['customer']) && ($this->request->params['prefix'] == 'customer')) {
            if ($this->Session->check('Auth.User')) {
                $this->set('authUser', $this->Auth->user());
                $loggedin = $this->Session->read('Auth.User');
                $this->set(compact('loggedin'));
                $this->layout = 'customer';
            }
        } else {
            $this->Auth->allow();
            $this->theme = 'Mariaquedisse';
        }
    }

    public function isAuthorized($user) {
        if (($this->params['prefix'] === 'admin') && ($user['role'] != 'admin')) {
            $this->Auth->logout();
            $this->redirect('/admin');
        }
        if (($this->params['prefix'] === 'customer') && ($user['role'] != 'customer')) {
            $this->Auth->logout();
            $this->redirect('/shop/login');
        }
        return true;
    }

    /* -------------------------------- Administração ----------------------------------------------------- */

    protected function __list() {
        
    }

    /**
     * Lista todos os "usuarios".
     *
     * @method        admin_index
     * @version       1.0.0
     * @return void
     */
    public function admin_index() {
        $this->{$this->modelClass}->recursive = 2;
        $this->Prg->encode = true;
        $this->Prg->commonProcess();
        $options = array(
            'conditions' => $this->{$this->modelClass}->parseCriteria($this->passedArgs),
            'order' => array($this->modelClass . '.created' => 'DESC'),
        );
        $this->paginate = $options;
        ${$this->modelClass} = $this->paginate($this->modelClass);
        $this->set('title_for_layout', __($this->modelClass) . ' - ' . __('Index'));
        $this->__list();
        $this->set(Inflector::variable(Inflector::underscore(Inflector::pluralize($this->modelClass))), ${$this->modelClass});
    }

    /**
     * Lista todos os "usuarios".
     *
     * @method        admin_index
     * @version       1.0.0
     * @return void
     */
    public function admin_view($id = null) {
        
        if (!$this->{$this->modelClass}->exists($id)) {
            throw new NotFoundException(__('Inválido') . ' ' . __($this->modelClass));
        }
        $this->{$this->modelClass}->recursive = 2;
        $this->set('title_for_layout', __($this->modelClass) . ' - ' . __('View'));
        $this->__list();
        $this->set(Inflector::variable(Inflector::underscore(Inflector::singularize($this->modelClass))), $this->{$this->modelClass}->findById($id));
    }

    /**
     * Cadastrar "usuarios"
     *
     * @method        admin_add
     * @version       1.0.0
     * @return void
     */
    public function admin_add() {
        if ($this->request->is('post')) {
            if ($this->{$this->modelClass}->save($this->request->data)) {
                $this->Session->setFlash(__('%s cadastrado com sucesso.', __($this->modelClass)), 'alert', array('plugin' => 'BoostCake', 'class' => 'alert-success'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Não foi possível cadastrar o %s.', __($this->modelClass)), 'alert', array('plugin' => 'BoostCake', 'class' => 'alert-danger'));
            }
        }
        $this->__list();
        $this->set('title_for_layout', __($this->modelClass) . ' - ' . __('New'));
    }

    /**
     * Alterar de acordo com o ID  "usuarios" especifico.
     *
     * @method        admin_edit
     * @version       1.0.0
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_edit($id = null) {
        if (!$this->{$this->modelClass}->exists($id)) {
            throw new NotFoundException(__('Inválido') . ' ' . __($this->modelClass));
        }
        if ($this->request->is(array('post', 'put'))) {
            if ($this->{$this->modelClass}->save($this->request->data)) {
                $this->Session->setFlash(__('%s alterado com sucesso.', __($this->modelClass)), 'alert', array('plugin' => 'BoostCake', 'class' => 'alert-success'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Não foi possível alterar o %s.', __($this->modelClass)), 'alert', array('plugin' => 'BoostCake', 'class' => 'alert-danger'));
            }
        } else {
            $this->{$this->modelClass}->recursive = 2;
            $options = array('conditions' => array($this->modelClass . '.' . $this->{$this->modelClass}->primaryKey => $id));
            $this->request->data = $this->{$this->modelClass}->find('first', $options);
        }
        $this->__list();
        $this->set('title_for_layout', __($this->modelClass) . ' - ' . __('Edit'));
    }

    /**
     * Excluir de acordo com o ID  "usuarios" especifico.
     *
     * @method        admin_delete
     * @version       1.0.0
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function admin_delete($id = null) {
        $this->{$this->modelClass}->id = $id;
        if (!$this->{$this->modelClass}->exists()) {
            $this->Session->setFlash(__('%s invalido.', __($this->modelClass)), 'alert', array('plugin' => 'BoostCake', 'class' => 'alert-danger'));
        } else {
            if ($this->{$this->modelClass}->saveField('status', 9)) {
                $this->Session->setFlash(__('%s excluido com sucesso.', __($this->modelClass)), 'alert', array('plugin' => 'BoostCake', 'class' => 'alert-success'));
            } else {
                $this->Session->setFlash(__('Não foi possivel excluir o %s.', __($this->modelClass)), 'alert', array('plugin' => 'BoostCake', 'class' => 'alert-danger'));
            }
        }
        $this->redirect($this->referer());
    }

    /**
     * Exportar dados do banco em formato CSV da tabela "usuarios".
     *
     * @method        admin_export_data
     * @version       1.0.0
     * @return void
     */
    public function admin_export() {
        $data = $this->{$this->modelClass}->find('all');
        $this->Export->exportCsv($data, $this->modelClass . '.csv');
    }

}
